package com.paishen.peiniwan.module.date;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.paishen.common.dialog.LoadingDialog;
import com.paishen.common.dialog.ShareDialog;
import com.paishen.common.util.BaseUtil;
import com.paishen.common.util.DateUtil;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.BusEvent;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.Once;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.HttpResp;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.Book;
import com.paishen.peiniwan.frame.http.entity.DateInfo;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.paishen.common.widget.MaterialHeader;
import com.paishen.peiniwan.frame.widget.StarView;
import com.paishen.common.widget.TitleLayout;
import com.paishen.peiniwan.module.profile.ProfileInfoActivity;
import com.squareup.okhttp.Request;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import jp.wasabeef.recyclerview.animators.FadeInLeftAnimator;

public class DateChooseActivity extends BaseActivity {
    public static final String EXTRA_ORDER_ID = "extra_order_id";
    private long orderId;

    private PtrFrameLayout layPtrFrame;
    private RecyclerView viewRecycler;
    private DateInfoAdapter adapter;

    private ShareDialog dlgShare;
    private AlertDialog dlgRepeal;
    private View layRepeal;

    private ViewGroup layOnce;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        orderId = getIntent().getLongExtra(EXTRA_ORDER_ID, -1);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_date_choose);

        ImageView viewShare = (ImageView) LayoutInflater.from(this).inflate(R.layout.layout_title_menu_image, null);
        viewShare.setImageResource(R.mipmap.date_share);
        viewShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShareDialog();
            }
        });

        TitleLayout layTitle = (TitleLayout) findViewById(R.id.lay_title);
        layTitle.pushContent(makeBackView(), getString(R.string.date_choose_target), viewShare, false);

        layRepeal = findViewById(R.id.lay_repeal);

        viewRecycler = (RecyclerView) findViewById(R.id.view_recycler);
        viewRecycler.setLayoutManager(new LinearLayoutManager(this));
        viewRecycler.setAdapter(adapter = new DateInfoAdapter());
        viewRecycler.setItemAnimator(new FadeInLeftAnimator(new OvershootInterpolator(1f)));

        layPtrFrame = (PtrFrameLayout) findViewById(R.id.lay_ptr_frame);
        MaterialHeader header = new MaterialHeader(this);
        int[] colors = new int[]{0xFF05131A};
        header.setColorSchemeColors(colors);
        header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
        header.setPadding(0, BaseUtil.dip2px(15), 0, BaseUtil.dip2px(10));
        header.setPtrFrameLayout(layPtrFrame);
        layPtrFrame.setDurationToCloseHeader(1500);
        layPtrFrame.setHeaderView(header);
        layPtrFrame.addPtrUIHandler(header);
        layPtrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, viewRecycler, header);
            }

            @Override
            public void onRefreshBegin(final PtrFrameLayout frame) {
                requestOrderInfo();
            }
        });

        layPtrFrame.post(new Runnable() {
            @Override
            public void run() {
                layPtrFrame.autoRefresh();
            }
        });

        findViewById(R.id.tx_repeal).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showRepealDialog();

            }
        });

        layOnce = (ViewGroup) findViewById(R.id.lay_once);
        Once.getInstance().coverDateChoose(this, layOnce);
    }

    private void showRepealDialog() {
        if (dlgRepeal == null) {
            dlgRepeal = new AlertDialog.Builder(this).setTitle(R.string.tips).setMessage(R.string.date_choose_repeal_message)
                    .setCancelable(false).setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dlgRepeal.dismiss();
                            requestOrderRepeal(orderId);
                        }
                    }).setNegativeButton(R.string.date_choose_cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dlgRepeal.dismiss();
                        }
                    }).create();
        }
        dlgRepeal.show();
    }

    private void requestOrderRepeal(long oid) {
        final LoadingDialog dlgLoading = new LoadingDialog.Builder(DateChooseActivity.this).setCanCancel(false).create();
        dlgLoading.show();

        PnwHttpManager.Order.repeal(TAG, oid, new PnwOkCallbackAdapter<HttpResp>() {
            @Override
            public void onResponse(HttpResp response, boolean fresh) {
                super.onResponse(response, fresh);
                dlgLoading.dismiss();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    adapter.notifyItemRangeRemoved(0, adapter.getItemCount());
                    adapter.dateInfo = null;

                    EventBus.getDefault().post(new BusEvent(BusEvent.ACTION_REFRESH_MAIN_PROFILE_DATE));
                    viewRecycler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            finish();
                        }
                    }, 400);
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                dlgLoading.dismiss();
            }
        });
    }

    private void showShareDialog() {
        if (dlgShare == null) {
            dlgShare = new ShareDialog.Builder(this).setCallback(new ShareDialog.OnShareClickListener() {
                @Override
                public void onPlatformClick(SHARE_MEDIA platform) {
                    UMImage image = new UMImage(DateChooseActivity.this, PnwHttpManager.URL_SERVICE_LOGO);
                    new ShareAction(DateChooseActivity.this).setPlatform(platform)
                            .withText(App.i().getString(R.string.share_content))
                            .withTitle(App.i().getUser().getNickname() + App.i().getString(R.string.date_share))
                            .withTargetUrl(PnwHttpManager.URL_SERVICE_SHARE + orderId)
                            .withMedia(image)
                            .setCallback(umShareListener)
                            .share();

                    dlgShare.dismiss();
                }
            }).create();
        }

        dlgShare.show();
    }

    private void requestOrderInfo() {
        PnwHttpManager.Order.info(TAG, orderId, new PnwOkCallbackAdapter<HttpRespData<DateInfo>>() {
            @Override
            public void onResponse(HttpRespData<DateInfo> response, boolean fresh) {
                super.onResponse(response, fresh);
                layPtrFrame.refreshComplete();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    adapter.set(response.data);

                    if (response.data.status == C.date.WAIT_RESPONSE_1) {
                        layRepeal.setVisibility(View.VISIBLE);
                    }
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                layPtrFrame.refreshComplete();
            }
        });
    }


    private static final class DateInfoAdapter extends RecyclerView.Adapter<DateInfoAdapter.ViewHolder> {
        private final byte TYPE_SENDER = 1;
        private final byte TYPE_ACCEPTOR = 2;
        private final byte TYPE_ACCEPTOR_PAY = 3;
        private final ViewGroup.MarginLayoutParams lpSubject;
        private final int d5;

        private DateInfo dateInfo;

        DateInfoAdapter() {
            d5 = BaseUtil.dip2px(5);
            lpSubject = new ViewGroup.MarginLayoutParams(BaseUtil.dip2px(65), BaseUtil.dip2px(25));
            lpSubject.setMargins(0, 0, d5, 0);
        }

        public void set(DateInfo data) {
            dateInfo = data;
            notifyItemRangeChanged(0, getItemCount());
        }

        public void append(DateInfo data) {
            if (dateInfo == null) {
                set(data);
                return;
            }
            final int size = dateInfo.book.size();
            dateInfo.book.addAll(data.book);
            notifyItemRangeChanged(size - 1, data.book.size());
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public ViewHolder(View view) {
                super(view);
            }
        }

        public class ViewHolderSender extends DateInfoAdapter.ViewHolder {
            public ViewHolderSender(View view) {
                super(view);
            }

            private TextView txNickname, txTime, txLocation, txResponderCount;
            private View layGift;
            private ImageView imgGift;
            private TextView txGiftValue;
            private ImageView imgAvatar;
            private ViewGroup laySubject;
        }

        public class ViewHolderContent extends DateInfoAdapter.ViewHolder implements View.OnClickListener {
            public ViewHolderContent(View view) {
                super(view);
                view.setOnClickListener(this);
            }

            private ImageView imgAvatar;
            private TextView txNickname;
            private Button btnUp;
            private StarView viewStar;
            private TextView txConcern;
            private ImageView imgGift;
            private TextView txGiftValue;

            private long content_userid;

            @Override
             public void onClick(View v) {
                Intent intent = new Intent(v.getContext(), ProfileInfoActivity.class);
                intent.putExtra(ProfileInfoActivity.EXTRA_SHOWN_USER_ID, content_userid);
                v.getContext().startActivity(intent);
            }
        }

        @Override
        public int getItemCount() {
            return dateInfo != null ? dateInfo.book.size() + 1 : 0;
        }

        @Override
        public int getItemViewType(int position) {
            if (position == 0) {
                return TYPE_SENDER;
            }
            Book b = dateInfo.book.get(position - 1);
            boolean isResponderPay = b.gift != null;
            return isResponderPay ? TYPE_ACCEPTOR_PAY : TYPE_ACCEPTOR;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int mViewType) {
            switch (mViewType) {
                case TYPE_SENDER:
                    View viewHead = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_date_choose_sender, viewGroup, false);
                    ViewHolderSender vhHead = new ViewHolderSender(viewHead);
                    vhHead.txNickname = (TextView) viewHead.findViewById(R.id.tx_nickname);
                    vhHead.txTime = (TextView) viewHead.findViewById(R.id.tx_time);
                    vhHead.txLocation = (TextView) viewHead.findViewById(R.id.tx_location);
                    vhHead.txResponderCount = (TextView) viewHead.findViewById(R.id.tx_responder_count);
                    vhHead.imgAvatar = (ImageView) viewHead.findViewById(R.id.img_avatar);
                    vhHead.laySubject = (ViewGroup) viewHead.findViewById(R.id.lay_subject);
                    vhHead.layGift = viewHead.findViewById(R.id.lay_gift);
                    vhHead.imgGift = (ImageView) viewHead.findViewById(R.id.img_gift);
                    vhHead.txGiftValue = (TextView) viewHead.findViewById(R.id.tx_gift_value);
                    return vhHead;
                case TYPE_ACCEPTOR:
                case TYPE_ACCEPTOR_PAY:
                    int resLayoutId = mViewType == TYPE_ACCEPTOR ?
                            R.layout.recycler_date_choose_acceptor : R.layout.recycler_date_choose_acceptor_pay;
                    View viewContent = LayoutInflater.from(viewGroup.getContext()).inflate(resLayoutId, viewGroup, false);
                    ViewHolderContent vhContent = new ViewHolderContent(viewContent);
                    vhContent.imgAvatar = (ImageView) viewContent.findViewById(R.id.img_avatar);
                    vhContent.txNickname = (TextView) viewContent.findViewById(R.id.tx_nickname);
                    vhContent.txConcern = (TextView) viewContent.findViewById(R.id.tx_concern);
                    vhContent.btnUp = (Button) viewContent.findViewById(R.id.btn_up);
                    vhContent.btnUp.setOnClickListener(onUpClickListener);
                    vhContent.viewStar = (StarView) viewContent.findViewById(R.id.view_star);
                    vhContent.imgGift = (ImageView) viewContent.findViewById(R.id.img_gift);
                    vhContent.txGiftValue = (TextView) viewContent.findViewById(R.id.tx_gift_value);
                    return vhContent;
            }
            // if return null -> program crash
            return null;
        }

        @Override
        public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
            switch (getItemViewType(position)) {
                case TYPE_SENDER:
                    ViewHolderSender vhHead = (ViewHolderSender) viewHolder;
                    Glide.with(vhHead.itemView.getContext()).load(dateInfo.user.head_img_url).placeholder(R.mipmap.common_avatar_c_170).bitmapTransform(App.i().getCropCircleTransformation()).into(vhHead.imgAvatar);
                    vhHead.txNickname.setText(dateInfo.user.nickname);

                    vhHead.laySubject.removeAllViewsInLayout();
                    for (String subject : dateInfo.subject_type) {
                        vhHead.laySubject.addView(makeSubjectView(viewHolder.itemView.getContext(), subject));
                    }
                    String date_from = DateUtil.convert(dateInfo.date_from, DateUtil.yyyy_MM_dd_HH_mm_ss, DateUtil.yyyy_MM_dd_HH_mm);
                    vhHead.txTime.setText(date_from);
                    vhHead.txLocation.setText(dateInfo.address);

                    vhHead.txResponderCount.setText(App.i().getString(R.string.date_responder_count_2, String.valueOf(dateInfo.book_count)));

                    boolean isSenderPay = dateInfo.gift != null;
                    if (isSenderPay) {
                        vhHead.layGift.setVisibility(View.VISIBLE);
                        Glide.with(vhHead.itemView.getContext()).load(dateInfo.gift.image).fitCenter().into(vhHead.imgGift);
                        vhHead.txGiftValue.setText(vhHead.itemView.getContext().getString(R.string.date_pay_value_2, String.valueOf((int) dateInfo.gift.price)));
                    } else {
                        vhHead.layGift.setVisibility(View.GONE);
                    }

                    break;
                case TYPE_ACCEPTOR:
                case TYPE_ACCEPTOR_PAY:
                    ViewHolderContent vhContent = (ViewHolderContent) viewHolder;
                    Book b = dateInfo.book.get(position - 1);
                    Glide.with(vhContent.itemView.getContext()).load(b.user.head_img_url).placeholder(R.mipmap.common_avatar_c_170).bitmapTransform(App.i().getCropCircleTransformation()).into(vhContent.imgAvatar);
                    vhContent.content_userid = b.user.id;
                    vhContent.txNickname.setText(b.user.nickname);
                    vhContent.txConcern.setText(String.valueOf(b.user.collect_count));


                    if (getItemViewType(position) == TYPE_ACCEPTOR_PAY) {
                        Glide.with(vhContent.itemView.getContext()).load(b.gift.image).into(vhContent.imgGift);
                        vhContent.txGiftValue.setText(String.valueOf((int) b.gift.price));
                    }
                    vhContent.viewStar.setLightStarCount(b.user.good_rate);
                    vhContent.btnUp.setTag(b);
                    break;
            }
        }


        private View.OnClickListener onUpClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Book b = (Book) v.getTag();
                DateInfo e = new DateInfo();
                e.id = dateInfo.id;
                e.user = dateInfo.user;
                e.address = dateInfo.address;
                e.status = dateInfo.status;
                e.subject_type = dateInfo.subject_type;
                e.date_from = dateInfo.date_from;
                e.book = new ArrayList<>();
                e.book.add(b);

                boolean isResponderPay = b.gift != null;
                e.isself_pay = !isResponderPay;

                // choose 里面的逻辑有变化，虽然可以取到正确的价格(谁给钱)，但是交个服务器的selectUser获得价格更好。在DateInfoActivity里面

                Intent intent = new Intent(v.getContext(), DateInfoActivity.class);
                intent.putExtra(DateInfoActivity.EXTRA_DATE_INFO, e);
                v.getContext().startActivity(intent);
            }
        };


        private TextView makeSubjectView(Context context, String text) {
            TextView txSubject = new TextView(context);
            txSubject.setLayoutParams(lpSubject);
            txSubject.setTextColor(0xFFFFFFFF);
            txSubject.setTextSize(13);
            txSubject.setGravity(Gravity.CENTER);
            txSubject.setText(text);
            txSubject.setBackgroundResource(R.drawable.date_shape_subject);
            return txSubject;
        }
    }


    public void onEventMainThread(com.paishen.peiniwan.BusEvent event) {
        super.onEventMainThread(event);
        if (event.type == BusEvent.TYPE_MAIN_THREAD) {
            switch (event.action) {
                case BusEvent.ACTION_REFRESH_DATE_CHOOSE:
                    requestOrderInfo();
                    break;
            }
        }
    }


    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(App.i(), platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(App.i(), platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(App.i(), platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

}
